const express=require("express");
//引入数据模型
const User=require("../../model/user");
//引入加密名字   token
const key=require("../../config/key");
//引入passport 
const passport =require("passport");
//引入数据加密
const bcrypt=require("bcrypt");
//引入路由
const router=express.Router();
//引入jsonwebtoken
const jwt = require('jsonwebtoken');
//引入头像 gravatar
const gravatar=require("gravatar");
// route  /api/user/test
// @desc 返回请求的json数据
//@access  public
router.get("/test",(req,res)=>{
    res.json({
        msg:"我是test"
    })
});
// route post  /api/user/register
// @desc 返回请求的json数据
//@access  public
// 使用post 需要使用boby-parser插件 如果使用的是 express 生成器就不需要安装了
router.post("/register",(req,res)=>{
    // console.log(req.body);
    User.findOne({email:req.body.email}).then((user)=>{
        if(user){
            return res.status(400).json("邮箱已被注册")
        }else{
            const avatar=gravatar.url(req.body.email,{s: '200', r: 'pg', d: 'mm'})
            const newUser =new User({
                userName:req.body.userName,
                email:req.body.email,
                avatar,
                identity:req.body.identity,
                passWord:req.body.passWord
            });
            bcrypt.genSalt(10, function(err, salt) {
                bcrypt.hash(newUser.passWord, salt, (err, hash)=> {
                    if(err) throw err;
                    newUser.passWord=hash;
                    newUser.save().then((user)=>{
                        res.json({
                            user
                        })
                    }).catch((err)=>{
                        console.log(err);
                    })
                });
            });
        }
    });
});

// route post  /api/user/login
// @desc token jwt passpost
//@access  public
router.post("/login",(req,res)=>{
   let email=req.body.email;
   let passWord=req.body.passWord;
      User.findOne({email}).then((user)=>{
    if(!user){
       return res.status(400).json("用户不存在")
    }
    //密码匹配
    bcrypt.compare(passWord, user.passWord).then((isMath)=>{
        if(isMath){
            const rule={
                id:user.id,
                userName:user.userName,
                avatar:user.avatar,
                identity:user.identity
            }
            // jwt.sign("规则","加密名字","过期时间","箭头函数")
            jwt.sign(rule,key.encryptName,{expiresIn:3600*12},(err,token)=>{
                if(err) throw err;
                res.status(200).json({
                    token:"Bearer "+token,
                    success:true
                });
            })
        }else{
            res.status(500).json("密码错误！");
        }
    });
   });
});

// route post  /api/user/current
// @desc return current user
//@access  private
router.get("/current",passport.authenticate("jwt",{session:false}),(req,res)=>{
    res.json(
        {
            id:req.user.id,
            userName:req.user.userName,
            email:req.user.email,
            avatar:req.user.avatar,
            identity:req.user.identity
        }
    )
});
module.exports=router;